package Test;

class MyBlockQueue<E>{
    //实现带泛型的
    //实现普通的循环队列
   volatile private E[]array = null;
   volatile private int head = 0;
   volatile private int tail = 0;
    //创建一个数组
    private int size = 0;//记录长度
    public MyBlockQueue(int n) {
        array = (E[]) new Object[n];
    }
    //出队列,队列是弹出第一个元素
    synchronized public E take() throws InterruptedException {
        while (size == 0){
            //此时数组没有元素
            this.wait();//没有元素就阻塞
        }
        E p = array[head];
        head++;
        if(head == array.length){
            head = 0;
        }
        size--;
        this.notify();
        return p;
    }
    public E peek() throws InterruptedException {
        while (size == 0){
            //此时数组没有元素
            this.wait();
        }
        E p = array[head];
        this.notify();
        return p;
    }
   synchronized public void put(E value) throws InterruptedException {
        while (size == array.length){
            //此时满了
            this.wait();
        }
        array[tail] = value;
        tail++;
        if(tail == array.length){
            tail = 0;
        }
        size++;
        this.notify();
    }

}

public class Test5 {
    //编写代码实现阻塞队列
    //1.围绕循环队列实现
    //2.在满足不同的情况时进行wait和notify

    public static void main(String[] args) throws InterruptedException {
        MyBlockQueue<Integer> myBlockQueue = new MyBlockQueue<>(5);
        myBlockQueue.put(3);
        myBlockQueue.put(3);
        myBlockQueue.put(3);
        myBlockQueue.put(3);
        myBlockQueue.put(3);
        System.out.println(myBlockQueue.take());



    }
}
